package net.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;

public class UdpSocket {
	protected DatagramSocket dataSocket;
	protected DatagramPacket sentPacket;
	protected DatagramPacket recvPacket;
	
	protected final byte[] buf = new byte[65536];
	
	public UdpSocket() throws SocketException {
		
	}
	
	public UdpSocket(int bindPort) throws SocketException {
		dataSocket = new DatagramSocket(bindPort);
		
		sentPacket = new DatagramPacket(new byte[0], 0);
		recvPacket = new DatagramPacket(buf, buf.length);
	}
	
	public void setDestAddress(String host, int port){
		this.setDestAddress(new InetSocketAddress(host, port));
	}
	
	public void setDestAddress(SocketAddress socketAddress){
		sentPacket.setSocketAddress(socketAddress);
	}
	
	public void receive(){
		Thread thread = new Thread(){
			public void run(){
				while(true){
					try {
						dataSocket.receive(recvPacket);
						int len = recvPacket.getLength();
						handle(recvPacket.getSocketAddress(), recvPacket.getData(), 0, recvPacket.getLength());
					} catch (IOException e) {
						e.printStackTrace();
						break;
					}
				}
			}
		};
		thread.start();
	}
	
	protected void handle(SocketAddress socketAddress, byte[] buf, int offset, int length){
		System.out.println("RECEIVE "+socketAddress + " " + length + "-'" + new String(buf, 0, length)+"'" );
	}

	public void send(byte[] data, int offset, int length) throws IOException{
		sentPacket.setData(data, offset, length);
		dataSocket.send(sentPacket);
	}
	
	public static void main(String args[]) throws Exception{
		UdpSocket server = new UdpSocket(6000);
		server.receive();
		UdpSocket sender = new UdpSocket(6001);
		sender.receive();
		sender.setDestAddress("localhost", 6000);
		sender.send("1234567890abcd".getBytes(), 0, 10);
		sender.send("1234567890abcd".getBytes(), 0, 12);
		Thread.sleep(200);
		server.setDestAddress("localhost", 6001);
		server.send("xxxxx".getBytes(), 0, 5);
		Thread.sleep(1000);
		System.exit(0);
	}

	public byte[] getBuf() {
		return buf;
	}
	
}
